using System;
using System.Xml;

using DesignByContract;

using Outcoding.GraphGenerator.Entities;
using Outcoding.GraphGenerator.Util.Logging;

namespace Outcoding.GraphGenerator.Composition {
    public class PresentationBuilder : BuilderBase {

        #region Attributes 
        private string templateUrlAttr = "template-url";
        #endregion

        private string mNodeName = XmlTagNames.presentation.ToString();

        private string mNodePath{
            get{ 
                return "/" + mNodeName;
            }
        }

        private XmlNode mNode;

        public override void SelectNode(XmlDocument document) {
            Check.Require(document != null, "XmlDocument cannot be null.");

            this.mNode = document.SelectSingleNode(this.mNodePath);

            Check.Ensure(this.mNode != null, "Presentation node could not be created.");
        }

        public override void Compose() {
            try {
                this.BuildObject(mNode);
            } catch (PreconditionException preExc) {
                LogManager.Instance.LogWarning("Presentation entity could not be created; process aborted.", preExc);
            }
        }

        public override void Compose(XmlNode node) {
            throw new NotImplementedException("The method or operation is not implemented.");
        }

        public override void AppendToParent(object parent) {
            throw new NotImplementedException("The method or operation is not implemented.");
        }

        private void BuildObject(XmlNode presentationXmlNode) {
            Presentation presentation = new Presentation();
            try {
                if (presentationXmlNode.Attributes[templateUrlAttr] != null)
                    presentation.TemplatePath = this.ParseTemplateUrlAttribute(presentationXmlNode);
            } catch (DesignByContract.PreconditionException preExc) {
                //log error
                presentation = null;
                LogManager.Instance.LogError("Presentation object could not be created.", preExc);
            }

            this.mProduct = presentation;
        }

        private string ParseTemplateUrlAttribute(XmlNode presentationXmlNode) {
            Check.Require(presentationXmlNode.Attributes[templateUrlAttr] != null, templateUrlAttr + " attribute not present");
            return presentationXmlNode.Attributes[templateUrlAttr].Value;
        }
    }
}
